package app1.rapidsquare.com.activity;

import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import app1.rapidsquare.com.classes.User;
import app1.rapidsquare.com.Utility.Utility;
import app1.rapidsquare.com.activity.R;

/**
 * Created by Hikmat on 21.08.2014.
 */
public class WebViewActivity extends Activity {
    private WebView mWebView;
    private RelativeLayout mViewBackground;
    protected ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            ActionBar actionBar = getActionBar();
            if (actionBar != null)
                actionBar.hide();
        }

        setContentView(R.layout.activity_webview);

        mViewBackground = (RelativeLayout) findViewById(R.id.ViewBackground);

        String accessTokenUrl = String.format(
                Utility.LINKED_IN_AUTHORIZATION_CODE_URL_FORMAT, getResources()
                        .getString(R.string.linkin_in_app_id), "123State");


        mWebView = (WebView) findViewById(R.id.WebView);
        mWebView.setVerticalScrollBarEnabled(false);
        mWebView.setHorizontalScrollBarEnabled(false);
        mWebView.setWebViewClient(new MyWebViewClient());
        mWebView.getSettings().setJavaScriptEnabled(true);

        if (!Utility.isNullOrEmpty(accessTokenUrl))
            mWebView.loadUrl(accessTokenUrl);
        else {
            Intent intent = new Intent().putExtra("ResultToken", "");
            setResult(Utility.INVALID_ERROR_CODE, intent);
            mWebView.stopLoading();
            finish();
        }
        mWebView.getSettings().setSavePassword(false);
        mWebView.getSettings().setSaveFormData(false);

        mProgressDialog = new ProgressDialog(WebViewActivity.this);
        mProgressDialog.setMessage("Please wait");
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        setResult(RESULT_CANCELED);
        finish();
    }

    class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            boolean isRunningService = false;
            if (url.startsWith(Utility.LINKED_IN_REDIRECT_URI)) {
                LoadLinkedInResult(url);
                isRunningService = true;
            }

            if (!isRunningService)
                view.loadUrl(url);

            return true;
        }

        @Override
        public void onPageStarted(android.webkit.WebView view,
                                  java.lang.String url, android.graphics.Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            mViewBackground.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished(android.webkit.WebView view,
                                   java.lang.String url) {
            super.onPageFinished(view, url);
            mViewBackground.setVisibility(View.GONE);
        }

        @Override
        public void onReceivedSslError(WebView view,
                                       android.webkit.SslErrorHandler handler,
                                       android.net.http.SslError error) {
        }

        public void onReceivedError(android.webkit.WebView view, int errorCode,
                                    java.lang.String description, java.lang.String failingUrl) {
        }
    }

    private void LoadLinkedInResult(String url) {
        if (url.startsWith(Utility.LINKED_IN_REDIRECT_URI)) {

            Bundle values = Utility.parseUrl(url);

            String error = values.getString("error");
            if (error == null) {
                error = values.getString("error_type");
            }

            String errorMessage = values.getString("error_msg");
            if (errorMessage == null) {
                errorMessage = values.getString("error_description");
            }

            if (Utility.isNullOrEmpty(error)
                    && Utility.isNullOrEmpty(errorMessage)) {
                String authorizationCode = values.getString(Utility.CODE_KEY);
                mProgressDialog.show();
                new GetProfileData().execute(authorizationCode);

            } else if (error != null
                    && (error.equals("access_denied") || error
                    .equals("OAuthAccessDeniedException"))) {

            }
        }
    }

    private class GetProfileData extends AsyncTask<String, Void, User> {

        @Override
        protected User doInBackground(String... params) {
            String url = String.format(Utility.LINKED_IN_ACCESS_TOKEN_URL_FORMAT,
                    params[0], getResources()
                            .getString(R.string.linkin_in_app_id), getResources()
                            .getString(R.string.linkin_in_app_secret_key));
            String line = "";
            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(url);
                httppost.addHeader("Content-type", "text/plain");
                httppost.setEntity(null);
                HttpResponse response = httpClient.execute(httppost);

                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        response.getEntity().getContent(), Utility.UTF8));
                String readLine = "";
                while ((readLine = reader.readLine()) != null) {
                    line += readLine;
                }
                reader.close();

            } catch (Exception e) {
                Utility.Log("get user profile data in WebViewActivity", e);
            }
            User user = new User();
            try {

                JSONObject jsonObject = new JSONObject(line);
                if (jsonObject.has("access_token")) {

                    url = String.format(Utility.LINKED_IN_ACCOUNT_URI, jsonObject.getString("access_token"));
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpGet httpGet = new HttpGet(url);
                    HttpResponse response = httpClient.execute(httpGet);

                    BufferedReader reader = new BufferedReader(new InputStreamReader(
                            response.getEntity().getContent(), Utility.UTF8));
                    String readLine = "";
                    line = "";
                    while ((readLine = reader.readLine()) != null) {
                        line += readLine;
                    }
                    reader.close();

                    if (!Utility.isNullOrEmpty(line)) {
                        JSONObject jsonObjectAccount = new JSONObject(line);
                        if (jsonObjectAccount.has("firstName"))
                            user.FirstName = jsonObjectAccount.getString("firstName");
                        if (jsonObjectAccount.has("lastName"))
                            user.LastName = jsonObjectAccount.getString("lastName");
                        if (jsonObjectAccount.has("headline")) {
                            String[] splitTitleAndCompany = jsonObjectAccount.getString("headline").split(" at ");
                            if (splitTitleAndCompany.length == 2) {
                                user.Title = splitTitleAndCompany[0];
                                user.Company = splitTitleAndCompany[1];
                            } else
                                user.Title = jsonObjectAccount.getString("headline");
                        }
                    }

                    url = String.format(Utility.LINKED_IN_ACCOUNT_PROFILE_URI, jsonObject.getString("access_token"));
                    httpClient = new DefaultHttpClient();
                    httpGet = new HttpGet(url);
                    response = httpClient.execute(httpGet);

                    reader = new BufferedReader(new InputStreamReader(
                            response.getEntity().getContent(), Utility.UTF8));
                    line = "";
                    while ((readLine = reader.readLine()) != null) {
                        line += readLine;
                    }
                    reader.close();

                    if (!Utility.isNullOrEmpty(line)) {
                        JSONObject jsonObjectAccount = new JSONObject(line);
                        if (jsonObjectAccount.has("emailAddress"))
                            user.Email = jsonObjectAccount.getString("emailAddress");
                        if (jsonObjectAccount.has("publicProfileUrl"))
                            user.LinkedInId = jsonObjectAccount.getString("publicProfileUrl");
                        if (jsonObjectAccount.has("pictureUrl"))
                            user.ImageUrl = jsonObjectAccount.getString("pictureUrl");

                    }

                    user.LinkedInName = user.FirstName + " " + user.LastName;
                    user.SocialType = Utility.SocialType.LinkedIn.value;
                }
            } catch (Exception ex) {
                Utility.Log("Convert String value to Json  in WebViewActivity", ex);
                return null;
            }
            return user;
        }

        @Override
        protected void onPostExecute(User user) {

            if (user != null) {
                setResult(Activity.RESULT_OK, new Intent().putExtra(
                        Utility.LINKED_IN_INTENT_DATA_NAME, user));
            } else {
                setResult(Activity.RESULT_CANCELED);
            }
            mProgressDialog.dismiss();
            finish();
        }
    }

}
